package com.shiikong_memory.yez.Arknights;

import com.alibaba.fastjson2.JSONObject;
import com.shiikong_memory.yez.Arknights.SklandAPI;
import com.shiikong_memory.yez.MySQLAPI.DaoImpl.SklandServer;
import love.forte.simbot.component.kook.event.KookChannelMessageEvent;
import love.forte.simbot.kook.api.message.SendChannelMessageApi;
import love.forte.simbot.quantcat.common.annotations.ContentTrim;
import love.forte.simbot.quantcat.common.annotations.Listener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Controller
@RequestMapping("/login")
public class WebLogin {

    @Autowired
    SklandAPI sklandAPI;

    @Autowired
    SklandServer sklandServer;

    //域名
    @Value("${property.domainname:http://127.0.0.1:8001}")
    private String DomaiNname;

    private Map<String, KookChannelMessageEvent> uuidMap = new HashMap<>();

    @Listener
    @ContentTrim
    public CompletableFuture<?> login(KookChannelMessageEvent event){
        if (event.getSourceEvent().getContent().matches("^登录鹰角通行证$")){
            UUID uuid = UUID.randomUUID();
            uuidMap.put(uuid.toString(), event);
            String s = Json.formatted(event.getAuthor().getId().toString(), "http://"+DomaiNname+"/login?uuid="+uuid.toString());
            return event.getContent().sendAsync(SendChannelMessageApi.create(10,event.getSourceEvent().getTargetId(), s));
        }
        return null;
    }


    @RequestMapping(method = RequestMethod.GET, path = "")
    public String home(@RequestParam("uuid") String uuid, Model model) {
        if (uuidMap.containsKey(uuid)){
            model.addAttribute("uuid", uuid);
            return "login";
        }
        model.addAttribute("msgs", "链接已被使用过,或链接不存在");
        return "404";
    }

    @RequestMapping(method = RequestMethod.POST , path ="/getCode")
    @ResponseBody
    public String getCode(@RequestParam("phone") String phone, @RequestParam("uuid") String uuid){
        if (!uuidMap.containsKey(uuid)) return "uuid失效或uuid不存在";
        JSONObject jsonObject2 = sklandAPI.getPhoneCode(phone);
        KookChannelMessageEvent event = uuidMap.get(uuid);
        if (jsonObject2.getInteger("status") == 0) {
            return "验证码已发送";
        }
        return jsonObject2.getString("msg");
    }

    @RequestMapping(method = RequestMethod.POST , path ="/login_phone")
    @ResponseBody
    public String login_phone(@RequestParam("phone") String phone,@RequestParam("code") String code, @RequestParam("uuid") String uuid){
        if (!uuidMap.containsKey(uuid)) return "uuid失效或uuid不存在";
        JSONObject jsonObject2 = sklandAPI.getToken_phone(phone, code);
        KookChannelMessageEvent event = uuidMap.get(uuid);
        if (jsonObject2.getInteger("status") == 0) {
            String id = jsonObject2.getJSONObject("data").getString("token");
            if (!sklandAPI.verifyToken(id)){
                return "鹰角通行证Token不合法请重新获取";
            }else {
                if (sklandServer.getByKookId(event.getAuthor().getId().toString()) == null){
                    boolean b = sklandServer.addSkland(event.getAuthor().getId().toString(), event.getAuthor().getName(), id, event.getBot().getId().toString());
                    if (b) {
                        uuidMap.remove(uuid);
                        event.getContent().sendAsync(SendChannelMessageApi.create(9,event.getSourceEvent().getTargetId(), "(met)%s(met) 鹰角通行证登录成功".formatted(event.getAuthor().getId().toString())));
                        return  "登录成功,鹰角通行证Token已保存云端,已开启森空岛自动签到功能\n检测到为新用户，开始自动签到";
                    }
                    else return "鹰角通行证token无法保存到云端，请联系管理者进行修复";
                }else {
                    boolean b = sklandServer.updateByKookId(event.getAuthor().getId().toString(), id);
                    if (b) {
                        uuidMap.remove(uuid);
                        event.getContent().sendAsync(SendChannelMessageApi.create(9,event.getSourceEvent().getTargetId(), "(met)%s(met) 鹰角通行证登录成功".formatted(event.getAuthor().getId().toString())));
                        return "登录成功,云端已更新保存鹰角通行证Token";
                    }
                    else return "云端已无法更新保存鹰角通行证Token，请联系管理者进行修复";
                }
            }
        }
        return jsonObject2.getString("msg");
    }

    @RequestMapping(method = RequestMethod.POST , path ="/login")
    @ResponseBody
    public String login(@RequestParam("phone") String phone,@RequestParam("password") String password, @RequestParam("uuid") String uuid){
        if (!uuidMap.containsKey(uuid)) return "uuid失效或uuid不存在";
        JSONObject jsonObject2 = sklandAPI.getToken(phone, password);
        KookChannelMessageEvent event = uuidMap.get(uuid);
        if (jsonObject2.getInteger("status") == 0) {
            String id = jsonObject2.getJSONObject("data").getString("token");
            if (!sklandAPI.verifyToken(id)){
                return "鹰角通行证Token不合法请重新获取";
            }else {
                if (sklandServer.getByKookId(event.getAuthor().getId().toString()) == null){
                    boolean b = sklandServer.addSkland(event.getAuthor().getId().toString(), event.getAuthor().getName(), id, event.getBot().getId().toString());
                    if (b) {
                        uuidMap.remove(uuid);
                        event.getContent().sendAsync(SendChannelMessageApi.create(9,event.getSourceEvent().getTargetId(), "(met)%s(met) 鹰角通行证登录成功".formatted(event.getAuthor().getId().toString())));
                        return  "登录成功,鹰角通行证Token已保存云端,已开启森空岛自动签到功能\n检测到为新用户，开始自动签到";
                    }
                    else return "鹰角通行证token无法保存到云端，请联系管理者进行修复";
                }else {
                    boolean b = sklandServer.updateByKookId(event.getAuthor().getId().toString(), id);
                    if (b) {
                        uuidMap.remove(uuid);
                        event.getContent().sendAsync(SendChannelMessageApi.create(9,event.getSourceEvent().getTargetId(), "(met)%s(met) 鹰角通行证登录成功".formatted(event.getAuthor().getId().toString())));
                        return "登录成功,云端已更新保存鹰角通行证Token";
                    }
                    else return "云端已无法更新保存鹰角通行证Token，请联系管理者进行修复";
                }
            }
        }
        return jsonObject2.getString("msg");
    }


    private String Json = """
            [
              {
                "type": "card",
                "theme": "secondary",
                "size": "lg",
                "modules": [
                  {
                    "type": "section",
                    "text": {
                      "type": "kmarkdown",
                      "content": "(met)%s(met)  **点击前往获取鹰角通行证**\\n注意：该链接只能使用一次，且只能由本人使用"
                    },
                    "mode": "right",
                    "accessory": {
                      "type": "button",
                      "theme": "primary",
                      "text": {
                        "type": "plain-text",
                        "content": "前往登录"
                      },
                      "value": "%s",
                      "click": "link"
                    }
                  }
                ]
              }
            ]
            """;
}
